<template>
  <v-container>
    <v-row>
      <v-col cols="12">
        <v-btn color="primary" @click="$router.push('/')" class="mb-4">
          <v-icon start>mdi-home</v-icon>返回主页
        </v-btn>
      </v-col>
    </v-row>
    <v-row>
      <v-col cols="12">
        <v-card>
          <v-card-title class="text-h5 d-flex align-center">
            <v-img
              src="../ico/logo.png"
              alt="Logo"
              width="32"
              height="32"
              class="mr-3 logo-img"
            ></v-img>
            <v-icon start>mdi-calendar-clock</v-icon>
            会议室预约
          </v-card-title>
          
          <v-card-text>
            <!-- 会议室选择 -->
            <v-row>
              <v-col cols="12" md="6">
                <v-select
                  v-model="selectedRoomId"
                  :items="availableRooms"
                  item-title="roomName"
                  item-value="id"
                  label="选择会议室"
                  :rules="[rules.required]"
                  @update:model-value="onRoomChange"
                ></v-select>
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field
                  v-model="selectedDate"
                  type="date"
                  label="选择日期"
                  @change="onDateChange"
                ></v-text-field>
              </v-col>
            </v-row>
            <!-- 新增会议主题输入框 -->
            <v-row>
              <v-col cols="12">
                <v-text-field
                  v-model="topic"
                  label="会议主题"
                  :rules="[rules.required]"
                  maxlength="50"
                  counter
                ></v-text-field>
              </v-col>
            </v-row>

            <!-- 时间块选择器 -->
            <v-row v-if="selectedRoomId && selectedDate">
              <v-col cols="12">
                <v-card variant="outlined" class="mt-4">
                                     <v-card-title class="text-subtitle-1 d-flex align-center">
                     <v-icon start>mdi-clock-outline</v-icon>
                     选择时间段
                     <v-spacer></v-spacer>
                     <v-chip color="primary" size="small">
                       已选择: {{ selectedTimeRange }}
                     </v-chip>
                   </v-card-title>
                   
                   <v-card-subtitle class="text-caption">
                     💡 提示：点击单个时间块或拖动选择连续时间段，每块10分钟，绿色表示可用，红色表示已被占用，蓝色表示已选择
                   </v-card-subtitle>
                  
                  <v-card-text>
                    <!-- 时间块网格 -->
                    <div class="time-grid">
                                             <div 
                         v-for="timeBlock in timeBlocks" 
                         :key="timeBlock.id"
                         :data-block-id="timeBlock.id"
                         class="time-block"
                         :class="{
                           'available': timeBlock.available,
                           'selected': timeBlock.selected,
                           'unavailable': !timeBlock.available,
                           'dragging': isDragging && timeBlock.available
                         }"
                         @mousedown="startDrag(timeBlock, $event)"
                         @mouseenter="onTimeBlockHover(timeBlock)"
                         @mouseup="endDrag"
                         @click="toggleTimeBlock(timeBlock)"
                       >
                        <div class="time-label">{{ timeBlock.label }}</div>
                        <div class="time-status">
                          <v-icon 
                            v-if="timeBlock.selected" 
                            size="small" 
                            color="white"
                          >
                            mdi-calendar-check
                          </v-icon>
                          <v-icon 
                            v-else-if="timeBlock.available" 
                            size="small" 
                            color="success"
                          >
                            mdi-check-circle
                          </v-icon>
                          <v-icon 
                            v-else 
                            size="small" 
                            color="error"
                          >
                            mdi-close-circle
                          </v-icon>
                        </div>
                      </div>
                    </div>

                    <!-- 快速选择按钮 -->
                    <div class="mt-4">
                      <v-btn-group>
                        <v-btn 
                          size="small" 
                          variant="outlined"
                          @click="selectTimeRange(1)"
                        >
                          1小时
                        </v-btn>
                        <v-btn 
                          size="small" 
                          variant="outlined"
                          @click="selectTimeRange(2)"
                        >
                          2小时
                        </v-btn>
                        <v-btn 
                          size="small" 
                          variant="outlined"
                          @click="selectTimeRange(3)"
                        >
                          3小时
                        </v-btn>
                        <v-btn 
                          size="small" 
                          variant="outlined"
                          @click="clearSelection"
                        >
                          清除选择
                        </v-btn>
                      </v-btn-group>
                    </div>
                  </v-card-text>
                </v-card>
              </v-col>
            </v-row>

            <!-- 预约信息预览 -->
            <v-row v-if="selectedTimeRange !== '未选择'">
              <v-col cols="12">
                <v-card variant="outlined" color="primary" class="mt-4">
                  <v-card-title class="text-subtitle-1">
                    <v-icon start>mdi-information</v-icon>
                    预约信息预览
                  </v-card-title>
                  <v-card-text>
                    <v-row>
                      <v-col cols="12" md="6">
                        <strong>会议室:</strong> {{ selectedRoomName }}
                      </v-col>
                      <v-col cols="12" md="6">
                        <strong>日期:</strong> {{ formatDate(selectedDate) }}
                      </v-col>
                      <v-col cols="12" md="6">
                        <strong>时间:</strong> {{ selectedTimeRange }}
                      </v-col>
                      <v-col cols="12" md="6">
                        <strong>时长:</strong> {{ calculateDuration() }}
                      </v-col>
                    </v-row>
                  </v-card-text>
                </v-card>
              </v-col>
            </v-row>

            <!-- 预约按钮 -->
            <v-row>
              <v-col cols="12" class="text-center">
                <v-btn
                  color="primary"
                  size="large"
                  :loading="loading"
                  :disabled="!canBook"
                  @click="bookRoom"
                >
                  <v-icon start>mdi-calendar-check</v-icon>
                  确认预约
                </v-btn>
              </v-col>
            </v-row>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>

    <!-- 预约成功对话框 -->
    <v-dialog v-model="showSuccessDialog" max-width="400">
      <v-card>
        <v-card-title class="text-h6 text-center">
          <v-icon color="success" class="mr-2">mdi-check-circle</v-icon>
          预约成功
        </v-card-title>
        <v-card-text class="text-center">
          会议室预约已成功创建！
        </v-card-text>
        <v-card-actions class="justify-center">
          <v-btn color="primary" @click="showSuccessDialog = false">
            确定
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 错误提示 -->
    <v-snackbar v-model="showError" color="error">
      {{ errorMessage }}
      <template v-slot:actions>
        <v-btn color="white" text @click="showError = false">
          关闭
        </v-btn>
      </template>
    </v-snackbar>

    <!-- 信息提示 -->
    <v-snackbar v-model="showInfo" color="info">
      {{ infoMessage }}
    </v-snackbar>
  </v-container>
</template>

<script>
import api from '../services/api.js'

export default {
  name: 'BookingPage',
  data() {
    return {
      selectedRoomId: null,
      selectedDate: '',
      timeBlocks: [],
      loading: false,
      showSuccessDialog: false,
      showError: false,
      errorMessage: '',
      availableRooms: [],
      isDragging: false,
      dragStartBlock: null,
      dragEndBlock: null,
      bookingConfig: {
        startHour: 9,
        endHour: 18,
        breakMinutes: 30,
        advanceDays: 7
      },
      rules: {
        required: v => !!v || '此字段为必填项'
      },
      checkedDates: {},
      showInfo: false,
      infoMessage: '',
      topic: ''
    }
  },
  computed: {
    selectedRoomName() {
      const room = this.availableRooms.find(r => r.id === this.selectedRoomId)
      return room ? room.roomName : ''
    },
    selectedTimeRange() {
      const selectedBlocks = this.timeBlocks.filter(block => block.selected)
      if (selectedBlocks.length === 0) return '未选择'
      
      const startBlock = selectedBlocks[0]
      const endBlock = selectedBlocks[selectedBlocks.length - 1]
      return `${startBlock.label} - ${endBlock.endLabel}`
    },
    canBook() {
      return this.selectedRoomId && 
             this.selectedDate && 
             this.timeBlocks.some(block => block.selected) && 
             this.topic &&
             !this.loading
    }
  },
  methods: {
    onRoomChange() {
      if (this.selectedRoomId && this.selectedDate) {
        this.fetchTimeBlocks()
      }
    },
    async onDateChange() {
      const date = this.selectedDate
      this.showInfoMessage('正在查询空闲信息…')
      if (!this.checkedDates[date]) {
        await this.fetchTimeBlocks()
        this.checkedDates[date] = true
      }
      // 2秒后自动关闭提示
      setTimeout(() => { this.showInfo = false }, 2000)
    },
    async fetchBookingConfig() {
      try {
        console.log('[请求] 获取会议室配置...')
        const response = await api.getBookingConfig()
        console.log('[响应] 会议室配置API响应:', response)
        if (response.data) {
          this.bookingConfig = response.data
          console.log('[处理] 获取会议室配置:', this.bookingConfig)
        }
      } catch (error) {
        console.error('[错误] 获取会议室配置失败:', error)
        // 使用默认配置
      }
    },
    async fetchRooms() {
      try {
        console.log('[请求] 获取会议室列表...')
        const response = await api.getAllRooms()
        console.log('[响应] 会议室API响应:', response)
        
        if (response.data && Array.isArray(response.data)) {
          this.availableRooms = response.data
          console.log('[处理] 设置会议室列表:', this.availableRooms)
        } else {
          console.error('[错误] API返回的数据格式不正确:', response.data)
          this.showErrorMessage('获取会议室列表失败：数据格式错误')
        }
      } catch (error) {
        console.error('[错误] 获取会议室列表失败:', error)
        if (error.response) {
          console.error('[错误响应]:', error.response.data)
          this.showErrorMessage(`获取会议室列表失败：${error.response.status} - ${error.response.data?.message || '未知错误'}`)
        } else {
          this.showErrorMessage('获取会议室列表失败，请稍后重试')
        }
      }
    },
    async fetchTimeBlocks() {
      try {
        this.loading = true
        const startTime = `${this.selectedDate}T00:00:00`
        const endTime = `${this.selectedDate}T23:59:59`
        console.log(`[请求] 获取空闲时段 roomId=${this.selectedRoomId}, start=${startTime}, end=${endTime}`)
        const response = await api.getFreeSlotsForRoom(
          this.selectedRoomId,
          startTime,
          endTime
        )
        console.log('[响应] 空闲时段API响应:', response)
        this.generateTimeBlocks(response.data)
      } catch (error) {
        console.error('[错误] 获取时间段失败:', error)
        this.showErrorMessage('获取时间段失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    generateTimeBlocks(freeSlots) {
      // 从配置生成时间块，每10分钟一个，显示所有时间段的占用情况
      this.timeBlocks = []
      const startHour = this.bookingConfig.startHour
      const endHour = this.bookingConfig.endHour
      
      for (let hour = startHour; hour < endHour; hour++) {
        for (let minute = 0; minute < 60; minute += 10) {
          const timeString = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
          const nextMinute = minute + 10
          const nextHour = nextMinute >= 60 ? hour + 1 : hour
          const nextMinuteStr = nextMinute >= 60 ? (nextMinute - 60).toString().padStart(2, '0') : nextMinute.toString().padStart(2, '0')
          const endTimeString = `${nextHour.toString().padStart(2, '0')}:${nextMinuteStr}`
          
          // 检查这个时间段是否可用
          const isAvailable = this.isTimeSlotAvailable(freeSlots, hour, minute)
          
          this.timeBlocks.push({
            id: `${hour}-${minute}`,
            hour: hour,
            minute: minute,
            label: timeString,
            endLabel: endTimeString,
            available: isAvailable,
            selected: false
          })
        }
      }
    },
    isTimeSlotAvailable(freeSlots, hour, minute) {
      // 检查指定时间段是否在空闲时段中
      // 数据库part字段：1-6表示每10分钟一个时间段
      // 前端：每10分钟一个时间段，直接对应
      const segment = Math.floor(minute / 10) + 1
      
      return freeSlots.some(slot => {
        const slotHour = parseInt(slot.hour)
        const slotSegment = parseInt(slot.segment)
        
        return slotHour === hour && slotSegment === segment
      })
    },
    toggleTimeBlock(block) {
      // 如果点击的是不可用的块，显示错误提示
      if (!block.available) {
        this.showErrorMessage(`该时间段已被占用：${block.label} - ${block.endLabel}`)
        return
      }
      
      // 如果点击的是已选择的块，取消选择
      if (block.selected) {
        block.selected = false
        return
      }
      
      // 找到连续的可选块
      const selectedBlocks = this.selectContinuousBlocks(block)
      
      // 更新选择状态
      this.timeBlocks.forEach(b => b.selected = selectedBlocks.includes(b.id))
    },
    selectContinuousBlocks(startBlock) {
      const selectedIds = []
      let currentIndex = this.timeBlocks.findIndex(b => b.id === startBlock.id)
      
      // 向前查找连续的可选块
      while (currentIndex >= 0 && this.timeBlocks[currentIndex].available) {
        selectedIds.push(this.timeBlocks[currentIndex].id)
        currentIndex--
      }
      
      // 向后查找连续的可选块
      currentIndex = this.timeBlocks.findIndex(b => b.id === startBlock.id) + 1
      while (currentIndex < this.timeBlocks.length && this.timeBlocks[currentIndex].available) {
        selectedIds.push(this.timeBlocks[currentIndex].id)
        currentIndex++
      }
      
      return selectedIds
    },
    startDrag(block, event) {
      // 如果开始拖拽的是不可用的块，显示错误提示
      if (!block.available) {
        this.showErrorMessage(`该时间段已被占用：${block.label} - ${block.endLabel}`)
        return
      }
      
      this.isDragging = true
      this.dragStartBlock = block
      this.dragEndBlock = block
      
      // 防止文本选择
      event.preventDefault()
      
      // 添加全局鼠标事件监听
      document.addEventListener('mousemove', this.onMouseMove)
      document.addEventListener('mouseup', this.endDrag)
    },
    
    onMouseMove(event) {
      if (!this.isDragging) return
      
      // 找到鼠标下的时间块
      const element = document.elementFromPoint(event.clientX, event.clientY)
      const timeBlockElement = element?.closest('.time-block')
      
      if (timeBlockElement) {
        const blockId = timeBlockElement.getAttribute('data-block-id')
        const block = this.timeBlocks.find(b => b.id === blockId)
        
        if (block) {
          // 如果拖拽到不可用的块，显示错误提示并停止拖拽
          if (!block.available) {
            this.showErrorMessage(`拖拽到已占用时间段：${block.label} - ${block.endLabel}`)
            this.endDrag()
            return
          }
          
          this.dragEndBlock = block
          this.updateDragSelection()
        }
      }
    },
    
    endDrag() {
      this.isDragging = false
      this.dragStartBlock = null
      this.dragEndBlock = null
      
      // 移除全局事件监听
      document.removeEventListener('mousemove', this.onMouseMove)
      document.removeEventListener('mouseup', this.endDrag)
    },
    
    updateDragSelection() {
      if (!this.dragStartBlock || !this.dragEndBlock) return
      
      const startIndex = this.timeBlocks.findIndex(b => b.id === this.dragStartBlock.id)
      const endIndex = this.timeBlocks.findIndex(b => b.id === this.dragEndBlock.id)
      
      const minIndex = Math.min(startIndex, endIndex)
      const maxIndex = Math.max(startIndex, endIndex)
      
      // 检查拖拽范围内是否有不可用的块
      for (let i = minIndex; i <= maxIndex; i++) {
        if (!this.timeBlocks[i].available) {
          this.showErrorMessage(`拖拽范围内包含已占用时间段：${this.timeBlocks[i].label} - ${this.timeBlocks[i].endLabel}`)
          this.endDrag()
          return
        }
      }
      
      // 更新选择状态
      this.timeBlocks.forEach((block, index) => {
        if (index >= minIndex && index <= maxIndex) {
          block.selected = block.available
        }
      })
    },
    
    onTimeBlockHover(block) {
      // 悬停效果，可以在这里添加预览功能
      if (this.isDragging && block.available) {
        this.dragEndBlock = block
        this.updateDragSelection()
      }
    },
    selectTimeRange(hours) {
      // 快速选择时间范围（从第一个可用时间块开始）
      const availableBlocks = this.timeBlocks.filter(block => block.available)
      if (availableBlocks.length === 0) {
        this.showErrorMessage('没有可用的时间段')
        return
      }
      
      const startBlock = availableBlocks[0]
      const startIndex = this.timeBlocks.findIndex(b => b.id === startBlock.id)
      const endIndex = Math.min(startIndex + hours * 6 - 1, this.timeBlocks.length - 1) // 每小时6个10分钟块
      
      // 检查范围内是否都是可用的
      for (let i = startIndex; i <= endIndex; i++) {
        if (!this.timeBlocks[i].available) {
          this.showErrorMessage('无法选择连续的时间段，存在已占用的时间段')
          return
        }
      }
      
      // 更新选择状态
      this.timeBlocks.forEach((block, index) => {
        block.selected = index >= startIndex && index <= endIndex && block.available
      })
    },
    clearSelection() {
      this.timeBlocks.forEach(block => block.selected = false)
    },
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      return d.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
      })
    },
    calculateDuration() {
      const selectedBlocks = this.timeBlocks.filter(block => block.selected)
      const minutes = selectedBlocks.length * 10
      const hours = Math.floor(minutes / 60)
      const remainingMinutes = minutes % 60
      
      if (hours > 0 && remainingMinutes > 0) {
        return `${hours}小时${remainingMinutes}分钟`
      } else if (hours > 0) {
        return `${hours}小时`
      } else {
        return `${remainingMinutes}分钟`
      }
    },
    async bookRoom() {
      try {
        this.loading = true
        const selectedBlocks = this.timeBlocks.filter(block => block.selected)
        if (selectedBlocks.length === 0) {
          this.showErrorMessage('请选择时间段')
          return
        }
        if (!this.topic) {
          this.showErrorMessage('请填写会议主题')
          return
        }
        const startBlock = selectedBlocks[0]
        const endBlock = selectedBlocks[selectedBlocks.length - 1]
        const startTime = `${this.selectedDate}T${startBlock.label}:00`
        const endTime = `${this.selectedDate}T${endBlock.endLabel}:00`
        const userId = 1 // 应该从用户状态获取
        await api.bookRoom(
          this.selectedRoomId,
          startTime,
          endTime,
          this.topic
        )
        this.showSuccessDialog = true
        this.clearSelection()
        this.topic = ''
      } catch (error) {
        console.error('预约失败:', error)
        this.showErrorMessage('预约失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    showErrorMessage(message) {
      this.errorMessage = message
      this.showError = true
    },
    showInfoMessage(msg) {
      this.infoMessage = msg
      this.showInfo = true
    }
  },
  async mounted() {
    // 设置默认日期为今天
    this.selectedDate = new Date().toISOString().split('T')[0]
    
    // 获取会议室配置
    await this.fetchBookingConfig()
    
    // 获取会议室数据
    this.fetchRooms()
  }
}
</script>

<style scoped>
.time-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(80px, 1fr));
  gap: 4px;
  margin-top: 16px;
}

.time-block {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 6px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  min-height: 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.time-block:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.time-block.available {
  border-color: #4caf50;
  background-color: #f1f8e9;
}

.time-block.available:hover {
  background-color: #e8f5e8;
}

.time-block.selected {
  border-color: #2196f3;
  background-color: #2196f3;
  color: white;
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(33, 150, 243, 0.4);
}

.time-block.unavailable {
  border-color: #f44336;
  background-color: #ffebee;
  cursor: not-allowed;
  opacity: 0.6;
}

.time-block.dragging {
  border-color: #2196f3;
  background-color: #e3f2fd;
  transform: scale(1.05);
  box-shadow: 0 6px 12px rgba(33, 150, 243, 0.3);
}

.time-grid {
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

.time-label {
  font-weight: bold;
  font-size: 10px;
  margin-bottom: 2px;
}

.time-status {
  display: flex;
  justify-content: center;
  align-items: center;
}

.v-btn-group {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.v-btn-group .v-btn {
  flex: 1;
  min-width: 80px;
}
</style> 